// Released in the Public Domain. http://creativecommons.org/licenses/publicdomain/
package org.xi8ix.async.spi;

import org.xi8ix.async.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Iain Shigeoka
 */
abstract class AbstractServer implements Server, SendFutureSender {
    // ------------------------
    // Core services/settings
    // ------------------------
    protected AsyncEngine engine;
    protected Receiver receiver;
    protected InetSocketAddress address;
    protected Tuner tuner = new TunerImpl(1024);
    protected Statistics statistics = new StatisticsImpl();

    // ------------------------
    // Packet management
    // ------------------------
    protected boolean closed;
    protected final Map<InetSocketAddress, AbstractPeer> peers = new HashMap<InetSocketAddress, AbstractPeer>();

    /**
     * Construct a new server object and initialize statistics for the server.
     *
     * @param address the address to bind to
     * @param receiver the link to use for the channel
     * @param engine the engine framework to use
     * @throws java.io.IOException if there was a problem creating the server
     */
    public AbstractServer(InetSocketAddress address, Receiver receiver, AsyncEngine engine) throws IOException {
        // Save core services
        this.address = address;
        this.receiver = receiver;
        this.engine = engine;
    }

    /**
     * Returns the peer associated with the given address.
     *
     * @param address the peer to retrieve
     * @return the peer found or null if no matching peer exists
     */
    public Peer getPeer(InetSocketAddress address) {
        return peers.get(address);
    }

    /**
     * Returns the addresses of all registered peers on this server.
     *
     * @return a set of all peer addresses managed by this server.
     */
    public Set<InetSocketAddress> getPeerAddresses() {
        return peers.keySet();
    }

    /**
     * Return the statistics of this server's sender.
     *
     * @return the statistics associated with this server.
     */
    public Statistics getStatistics() {
        return statistics;
    }

    /**
     * Return the tuner associated with this server's sender.
     *
     * @return the statistics associated with this server.
     */
    public Tuner getTuner() {
        return tuner;
    }
}
